今天會介紹 使用 AVCaptureMetadataOutput 物件辨識 QRCode
前幾天介紹的 AVCaptureMetadataOutputObjectsDelegate 裡的委派方法 metadataOutout 會被呼叫
定義 metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) function
unc metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
if let metadataObject = metadataObjects.first {
	// AVMetadataMachineReadableCodeObject 是從 Output 擷取到 Barcode 的內容
	guard let readableObject = metadataObject as? AVMetadataMachineReadableCodeObject else { return }
	for subView in scanQRCodeView.subviews{
		if subView.layer.name == "blackBackgroundView" {
			UIView.animate(withDuration: 0.5, animations: {
				subView.alpha = 0
			}) { (bool) in
				subView.removeFromSuperview()
				// 將讀取到的內容轉成字串
				guard let stringValue = readableObject.stringValue else { return }
				self.qrcodeString = stringValue
				// 以 Alert 的方式判別是否要開啟連結
				self.showAlertWith(title: "", message: "\(self.qrcodeString.description)", vc: self, confirmTitle: "Yes", cancelTitle: "No", confirm: {
					// 開啟連結
					if let url = URL(string: self.qrcodeString) {
						if self.qrcodeString.contains("http") || self.qrcodeString.contains("https") {
							UIApplication.shared.open(url, options: [:], completionHandler: nil)
						}
						else {
							let newURL = URL(string: "https://\(self.qrcodeString.description)")
							UIApplication.shared.open(newURL!, options: [:], completionHandler: nil)
						}
					}
				}, cancel: {
					self.scanQRCodeBlackView()
				})
			}
		}
	}
}
``
明天將會介紹 把常用的功能寫成一個方便呼叫的 function,並以 extension 的方式加在專案底下
GitHub - AVCaptureVideoPreviewLayerDemo